/**
 * Copyright (c) 2012 Nokia Corporation.
 */

package com.nokia.example.tictactoe.ui;

import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;

import com.nokia.example.tictactoe.console.TextWrapper;
import com.nokia.mid.ui.CanvasGraphicsItem;

/**
 * A text label. 
 */
public class TextLabel extends CanvasGraphicsItem {
	// Constants
	protected static final int MARGIN = 6;
	protected static final int MIN_WIDTH = MARGIN * 2;
	protected static final int DEFAULT_TEXT_COLOR = 0xffeeeeee;
	public static final int LEFT = 0;
	public static final int CENTER = 1;
	
	// Members
	protected TextWrapper _textWrapper = null;
	protected String _text = null;
	protected int _width = MIN_WIDTH;
	protected int _textColor = DEFAULT_TEXT_COLOR;
	protected int _alignment = LEFT;
	
	/**
	 * Constructor.
	 * @param width The label width.
	 */
	public TextLabel(int width, int height) {
		super(width, height);
		_textWrapper = TextWrapper.instance(Font.getDefaultFont(), width);
		setWidth(width);
	}
	
	/**
	 * From CanvasGraphicsitem.
	 */
	protected void paint(Graphics graphics) {
		if (_text == null || _text.length() == 0) {
			return;
		}
		
		_textWrapper.setWidth(_width);
		
		try {
			_textWrapper.setText(_text);
		}
		catch (IllegalArgumentException e) {
			System.out.println("TextLabel::paint(): TextWrapper::setText() failed!");
			return;
		}
		
		graphics.setColor(_textColor);
		int y = MARGIN;
		int x = 0;
		String line = null;
		
		while (_textWrapper.hasMoreLines()) {
			line = _textWrapper.nextLine();
			
			if (_alignment == CENTER) {
				x = (_width - _textWrapper.lineWidth(line)) / 2;
			}
			
			graphics.drawString(line, x + MARGIN, y, Graphics.TOP | Graphics.LEFT);
			y += _textWrapper.lineHeight();
		}
	}
	
	/** 
	 * @param text The text to set.
	 */
	public void setText(final String text) {
		_text = text;
		repaint();
	}
	
	/** 
	 * @param width The label width to set.
	 */
	public void setWidth(final int width) {
		if (width < MIN_WIDTH) {
			throw new IllegalArgumentException("The minimum width is " + MIN_WIDTH);
		}
		
		_width = width - MIN_WIDTH; // Leave margins
		repaint();
	}
	
	/** 
	 * @param alignment The vertical alignment of the text to set.
	 */
	public void setAlignment(final int alignment) {
		_alignment = alignment;
	}
	
	/** 
	 * @param color The text color to set.
	 */
	public void setTextColor(final int color) {
		_textColor = color;
	}
}
